import { useState, useEffect } from 'react';

const useData = (staticContext, getData, initial) => {
  const getInitialData = () => {
    if(staticContext) {
      console.log('server render')
      return staticContext
    }
    if(window.__APP_DATA) {
      console.log('client first render')
      return window.__APP_DATA
    }

    // 切换到新组件时要给一个默认值，这里根据各自页面传入，否则后续解构会报错
    return initial
  }

  const [data, setData] = useState(getInitialData())

  useEffect(() => {
    // 排除掉客户端首次渲染的情况，清空__APP_DATA
    if(window.__APP_DATA) {
      window.__APP_DATA = undefined
      return
    }

    // 否则都走组件请求数据
    console.log('spa render')
    getData().then(res => setData(res)).catch()
  }, []);

  return [data, setData]
}

export default useData